<template>
	<view>
		<u-datetime-picker :show="buyTimeShow" mode="date" @cancel="buyTimeShow = false"
			@confirm="changeBuyTime" :closeOnClickOverlay="true" @close="buyTimeShow = false"></u-datetime-picker>
		<u-collapse ref='coll' :value="['1','2','3']">
			<u-collapse-item name="1" title="基本信息" icon="https://project.gxrunxiang.com/cdn/car.png">
				<u-form ref="uForm" label-width="auto">
					<u-form-item label="名称"><u-input v-model="carDeatil.Name" /></u-form-item>
					<u-form-item label="厂家"><u-input v-model="carDeatil.Factory" /></u-form-item>
					<u-form-item label="型号"><u-input v-model="carDeatil.Model" /></u-form-item>
					<u-form-item label="车牌号"><u-input v-model="carDeatil.CarNo" /></u-form-item>
					<u-form-item label="车辆所属" @click="showAffiliation = true; "><u--input
							v-model="carDeatil.Affiliation" disabledColor="#ffffff" disabled /></u-form-item>
					<u-form-item label="车架号"><u-input v-model="carDeatil.Vin" /></u-form-item>
					<u-form-item label="发动机号"><u-input v-model="carDeatil.EngineNo" /></u-form-item>
					<u-form-item label="购买日期"  @click="buyTimeShow = true"><u-input v-model="carDeatil.BuyTime" :disabled="true" /></u-form-item>
					<!-- <u-form-item label="状态"><u-input v-model="carDeatil.Status" /></u-form-item> -->
					<u-form-item label="颜色"><u-input v-model="carDeatil.Color" /></u-form-item>
					<u-form-item label="备注"><u--textarea v-model="carDeatil.Remark" placeholder="请输入内容"
							height="180" maxlength="300"></u--textarea></u-form-item>
					<u-action-sheet :show="showAffiliation" :actions="dicAffiliation" title="请选择车辆所属" @close="showAffiliation = false"
						@select="affiliationSelect">
					</u-action-sheet>
				</u-form>
			</u-collapse-item>
			<u-collapse-item name="1" title="车辆整体照" icon="https://project.gxrunxiang.com/cdn/image.png">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					itype='车辆整体照' :sizeType='["compressed"]' :maxCount="10"></u-upload>
				<u-album :urls="imagesurls1"></u-album>
			</u-collapse-item>
			<u-collapse-item name="2" title="车架号照" icon="https://project.gxrunxiang.com/cdn/image.png">
				<u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" multiple itype='车架号照'
					:sizeType='["compressed"]' :maxCount="10"></u-upload>
				<u-album :urls="imagesurls2"></u-album>
			</u-collapse-item>
			<u-collapse-item name="3" title="行驶证照" icon="https://project.gxrunxiang.com/cdn/image.png">
				<u-upload :fileList="fileList3" @afterRead="afterRead" @delete="deletePic" name="3" multiple itype='行驶证照'
					:sizeType='["compressed"]' :maxCount="10"></u-upload>
				<u-album :urls="imagesurls3"></u-album>
			</u-collapse-item>
		</u-collapse>
		<u-button @click="submit">提交</u-button>
		<u-notify ref="uNotify"></u-notify>
	</view>
</template>
<script>
	import {
		baseUrl
	} from '@/common/config.js'
	import {
		mapGetters
	} from 'vuex'

	import {
		addcar,
		GetListByParent,
		getcarlist,
		carupdate,
		getfilebyoutid
	} from '@/common/api.js'
	export default {
		data() {
			return {
				itypelist: {
					"1": "车辆整体照",
					"2": "车架号照",
					"3": "行驶证照",
				},
				carDeatil: {},
				fileList1: [],
				fileList2: [],
				fileList3: [],
				imagesurls1: [],
				imagesurls2: [],
				imagesurls3: [],
				token: "",
				// dicStatus: [],
				dicAffiliation: [],
				showAffiliation: false,
				buyTimeShow: false,
				user: {},
				notifyData: {
					message: '保存成功',
					type: 'success',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 3000,
					safeAreaInsetTop: false
				},
			}
		},
		onLoad(option) {
			// GetListByParent("故障类型", this.dicStatus)
			GetListByParent("车辆所属", this.dicAffiliation)
			this.token = uni.getStorageSync("$token")
			if(option.Id){
				this.ischange = true
				this.changeId = option.Id
				this.getchangelist();
				getfilebyoutid(option.Id).then(res => {
					for (var i = 0; i < res.length; i++) {
						if (res[i].MyType == '车辆整体照') {
							this.imagesurls1.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
						else if (res[i].MyType == '车架号照') {
							this.imagesurls2.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
						else if (res[i].MyType == '行驶证照') {
							this.imagesurls3.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
					}
					setTimeout(() => {
							// console.log(this.$refs.coll)
							this.$refs.coll.init()				
						},
						1000)
				})
			}
		},
		onShow() {
			let user = JSON.parse(uni.getStorageSync("$userinfo"))
			this.user = user
		},
		methods: {
			affiliationSelect(e) {
				this.carDeatil.Affiliation = e.name
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {				console.log(event.name);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, this.itypelist[event.name])
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, itype) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}/SysFile/upload?outid=${this.carDeatil.Id||this.user.Id}&type=${itype}`,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Authorization": `Bearer ${this.token}`
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			submit() {
				if(this.ischange){
					carupdate(this.carDeatil).then(res => {
						this.$refs.uNotify.show(this.notifyData)
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					})
				}else{
					addcar(this.carDeatil).then((res) => {
						if (res === true) {
							uni.navigateBack()
						}
					})
				}
				
			},
			changeBuyTime(e){
				const timeFormat = uni.$u.timeFormat
				this.carDeatil.BuyTime = timeFormat(e.value, 'yyyy-mm-dd')
				this.buyTimeShow = false
			},
			async getchangelist(){
				let para = {
					Parameters: [{
						FieldName: "Id",
						ConditionalType: "Equal",
						FieldValue: this.changeId
					}],
					orderBys: ["Id"],
				}
				await getcarlist(para).then(res => {
					this.carDeatil = res.data[0]
				})
			},
		}
	}
</script>